<template>
  <div>
    <!--Breadcrumb面包屑组件-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row class="alertRow">
        <el-col>
          <el-alert
            :closable="false"
            title="注意: 只允许为第三级分类设置相关参数!"
            type="warning"
            show-icon
          >
          </el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            style="width: 30%"
            clearable
            v-model="selectedKeys"
            :options="cateList"
            :props="cateCascaderProp"
            @change="cateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!--tabs组件-->
      <el-tabs v-model="activeTabName" @tab-click="getParams">
        <el-tab-pane label="动态参数" name="many">
          <el-row class="addParamsBtn">
            <el-col>
              <el-button
                size="mini"
                type="primary"
                :disabled="!selectedKeys.length"
                @click="getAddParamsDialog"
                >添加参数</el-button
              >
            </el-col>
          </el-row>
          <el-table :data="tabData" stripe border>
            <el-table-column label="" type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="valsTabClose(scope.row, index)"
                  class="valsTag"
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <!--添加vals的input与button之间的切换-->
                <!--@keyup键盘按键弹起事件-->
                <!--blur失去焦点事件-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.addValsInputVisible"
                  v-model="scope.row.addValsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getEditParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleParamsDialogAndDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row class="addParamsBtn">
            <el-col>
              <el-button
                size="mini"
                :disabled="!selectedKeys.length"
                type="primary"
                @click="getAddParamsDialog"
                >添加属性</el-button
              >
            </el-col>
          </el-row>
          <el-table :data="tabData" stripe border>
            <el-table-column label="" type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="valsTabClose(scope.row, index)"
                  class="valsTag"
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <!--添加vals的input与button之间的切换-->
                <!--@keyup键盘按键弹起事件-->
                <!--blur失去焦点事件-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.addValsInputVisible"
                  v-model="scope.row.addValsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getEditParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleParamsDialogAndDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :visible.sync="addParamsDialog"
      :title="addParamsDialogTitle"
      @close="addParamsDialogColse"
    >
      <el-form
        label-width="80px"
        ref="addParamsFormRef"
        :rules="addParamsFormRules"
        :model="addParamsForm"
      >
        <el-form-item :label="addParamsDialogInputLabel" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="addParams">添 加</el-button>
        <el-button @click="addParamsDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="editParamsDialogTitle"
      :visible.sync="editParamsDialog"
      @close="editParamsDialogColse"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        label-width="80px"
        ref="editParamsFormRef"
      >
        <el-form-item :label="editParamsDialogInputLabel" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="editParams">修 改</el-button>
        <el-button @click="editParamsDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "params",
  data() {
    return {
      selectedKeys: [],
      cateList: [],
      cateCascaderProp: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      onlyParams: [],
      manyParams: [],
      activeTabName: "many",
      addParamsDialog: false,
      editParamsDialog: false,
      addParamsForm: {
        attr_name: "",
        attr_sel: "many"
      },
      addParamsFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur"
          },
          {
            min: 2,
            max: 8,
            message: "参数名称应在2~8个字符之间",
            trigger: "blur"
          }
        ]
      },
      editParamsFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入新参数名",
            trigger: "blur"
          },
          {
            min: 2,
            max: 8,
            message: "参数名称应在2~8个字符之间",
            trigger: "blur"
          }
        ]
      },
      editParamsForm: {
        attrId: ""
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getParams() {
      if (this.selectedKeys.length === 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: this.activeTabName }
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取参数失败，请重试!");
        res.data.forEach((item) => {
          if (item.attr_vals) {
            item.attr_vals = item.attr_vals.split(",");
          } else {
            item.attr_vals = [];
          }
          item.addValsInputVisible = false;
          item.addValsInputValue = "";
        });
        if (this.activeTabName === "many") {
          this.manyParams = res.data;
        } else if (this.activeTabName === "only") {
          this.onlyParams = res.data;
        }
      } else {
        this.selectedKeys = [];
        this.onlyParams = [];
        this.manyParams = [];
      }
    },
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: {}
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类失败，请重试!");
      this.cateList = res.data;
    },
    cateChange() {
      this.getParams();
    },
    editParams() {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid)
          return this.$message.error("表单预验证失败，请检查表单数据!");
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.paramsId}`,
          this.editParamsForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败，请重试!");
        }
        this.getParams();
        this.$message.success("修改成功!");
        this.editParamsDialog = false;
      });
    },
    deleParamsDialogAndDelete(row) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "删除用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${row.attr_id}`
          );
          if (res.meta.status !== 200)
            return this.$message.error("删除失败，请重试!");
          this.getParams();
          this.$message.success("删除成功!");
        })
        .catch(() => {
          this.$message("已取消删除");
        });
    },
    getAddParamsDialog() {
      this.addParamsForm.attr_sel = this.activeTabName;
      this.addParamsDialog = true;
    },
    async addParams() {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("表单验证失败!");
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          this.addParamsForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败，请重试!");
        }
        this.getParams();
        this.$message.success("添加参数成功!");
        this.addParamsDialog = false;
      });
    },
    addParamsDialogColse() {
      this.$refs.addParamsFormRef.resetFields();
    },
    async getEditParamsDialog(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        { params: { attr_sel: this.activeTabName } }
      );
      if (res.meta.status !== 200)
        return this.$message.error("参数异常,请重试!");
      this.editParamsForm = res.data;
      this.editParamsDialog = true;
    },
    editParamsDialogColse() {
      this.$refs.editParamsFormRef.resetFields();
    },
    showInput(row) {
      row.addValsInputVisible = true;
      // nextTick DOM更新渲染时，调用回调函数
      this.$nextTick((_) => {
        // 出现input时自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm(row) {
      const inputValue = row.addValsInputValue.trim(); // trim去除字符串两端的空格
      if (inputValue.length) {
        row.attr_vals.push(inputValue);
      }
      row.addValsInputValue = "";
      row.addValsInputVisible = false;
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(" "),
          attr_sel: this.activeTabName
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("添加失败，请重试");
    },
    valsTabClose(row, index) {
      row.attr_vals.splice(index, 1);
      this.handleInputConfirm(row);
    }
  },
  computed: {
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
      return "";
    },
    addParamsDialogTitle() {
      return this.activeTabName === "many" ? "添加参数" : "添加属性";
    },
    addParamsDialogInputLabel() {
      return this.activeTabName === "many" ? "动态参数" : "静态属性";
    },
    editParamsDialogTitle() {
      return this.activeTabName === "many" ? "修改动态参数" : "修改静态属性";
    },
    editParamsDialogInputLabel() {
      return this.activeTabName === "many" ? "动态参数" : "静态属性";
    },
    tabData() {
      return this.activeTabName === "many" ? this.manyParams : this.onlyParams;
    }
  }
};
</script>

<style scoped lang="less">
.alertRow {
  margin-bottom: 15px;
}
.addParamsBtn {
  margin-bottom: 10px;
}

.valsTag {
  margin-left: 15px;
}
.button-new-tag {
  margin-left: 15px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

/* 防止Tabs组件出现蓝色边框*/
/deep/.el-tabs__item:focus.is-active.is-focus:not(:active) {
  box-shadow: none;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}
</style>
